/**
 * dialog拖放指令
 * <el-dialog v-drag-dialog></el-dialog>
 */
const dragFunc = function (el, binding, vnode) {
  if (binding.value === false) {
    return;
  }
  const dialogHeaderEl = el.querySelector('.el-dialog__header');
  const dragDom = el.querySelector('.el-dialog');
  const outer = dragDom.parentNode;
  dialogHeaderEl.style.cursor = 'move';

  // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
  const sty = dragDom.currentStyle || window.getComputedStyle(dragDom, null);
  // sty.position = 'relative';
  // sty.margin = '0';
  // sty.top = '15vh';
  dialogHeaderEl.addEventListener('mousedown', function (e) {
    // 鼠标按下，计算当前元素距离可视区的距离
    const disX = e.clientX - dialogHeaderEl.offsetLeft;
    const disY = e.clientY - dialogHeaderEl.offsetTop;

    // 获取到的值带px 正则匹配替换
    let styL, styT;

    // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
    if (sty.left.includes('%')) {
      styL = +document.body.clientWidth * (+sty.left.replace(/\%/g, '') / 100);
      styT = +document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100);
    } else {
      styL = +sty.left.replace(/\px/g, '');
      styT = +sty.top.replace(/\px/g, '');
    };

    let mousemove = function (e) {
      // 通过事件委托，计算移动的距离 
      const l = e.clientX - disX;
      const t = e.clientY - disY;

      // 移动当前元素  
      dragDom.style.left = `${l + styL}px`;
      dragDom.style.top = `${t + styT}px`;
    };
    let mouseup = function () {
      document.removeEventListener('mousemove', mousemove);
      document.removeEventListener('mouseup', mouseup);
      //禁止对话框Title拖拽超出上边界
      if (outer.className.indexOf('edu-dialog_wrapper') > -1) {
        //处理edudialog
        let top = dragDom.style.top.replace('px', '')
        top = parseInt(top);
        let dialogHeight = dragDom.clientHeight;
        if (top < dialogHeight / 2) {
          dragDom.style.top = (dialogHeight / 2) + 'px'
        }
      } else {
        //处理普通el-dialog
        let marginTop = dragDom.style.marginTop;
        if (marginTop.indexOf('vh') > 0) {
          //默认marginTop的vh转换为px
          marginTop = marginTop.replace('vh', '')
          marginTop = parseInt(marginTop)
          marginTop = document.documentElement.clientHeight / 100 * marginTop
          //获取对话框top值
          let top = dragDom.style.top.replace('px', '')
          top = parseInt(top);
          //超出时设置
          if (marginTop + top < 0) {
            dragDom.style.top = (marginTop * -1) + 'px'
          }
        }
      }
    };
    document.addEventListener('mousemove', mousemove);
    document.addEventListener('mouseup', mouseup);
  });
}
export default {
  inserted: dragFunc,
  // componentUpdated: dragFunc
};
